package pri.hillchen.std.consurrent.util.handler;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import pri.hillchen.std.consurrent.util.HttpclientManager;

import java.io.IOException;

/**
 * Created by hillchen on 2018/2/10.
 */
public abstract  class AbstractResponseHandler<T> implements ResponseHandler<T>{
    private static Logger LOGGER = Logger.getLogger(AbstractResponseHandler.class);
    @Override
    public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        try {
            // 返回状态码
            int statusCode = response.getStatusLine().getStatusCode();
            switch (statusCode) {
                case 200:
                    return succHandle(response);
                case 206:
                    return succHandle(response);
                case 400:
                    LOGGER.error("下载400错误代码，请求出现语法错误.");
                    break;
                case 403:
                    LOGGER.error("下载403错误代码，资源不可用.");
                    break;
                case 404:
                    LOGGER.error("下载404错误代码，无法找到指定资源地址.");
                    break;
                case 503:
                    LOGGER.error("下载503错误代码，服务不可用.");
                    break;
                case 504:
                    LOGGER.error("下载504错误代码，网关超时.");
                    break;
                default:
                    LOGGER.error("未处理的错误,code=" + statusCode);
            }

        } finally {
            if (response != null) {
                try {
                    ((CloseableHttpResponse) response).close();
                } catch (IOException e) {
                    LOGGER.error("关闭响应错误.", e);
                }
            }
        }
        return null;
    }
    public abstract T succHandle(HttpResponse httpResponse) throws IOException ;
}
